use crate::{ConfigLoader, ConfigFormat, RustCloudConfig, ConfigSource, ConfigManager, ConfigManagerBuilder};
use crate::source::RemoteAuth;
use rustcloud_core::{RegistryConfig, RegistryType};
use tempfile::NamedTempFile;
use std::time::Duration;
use std::io::Write;

// ================== 配置加载器测试 ==================

#[test]
fn test_config_format_display() {
    assert_eq!(ConfigFormat::Toml.to_string(), "toml");
    assert_eq!(ConfigFormat::Yaml.to_string(), "yaml");
    assert_eq!(ConfigFormat::Json.to_string(), "json");
}

#[test]
fn test_config_format_from_extension() {
    assert_eq!(ConfigFormat::from_extension("toml"), Some(ConfigFormat::Toml));
    assert_eq!(ConfigFormat::from_extension("TOML"), Some(ConfigFormat::Toml));
    assert_eq!(ConfigFormat::from_extension("yaml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("YAML"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("yml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("YML"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("json"), Some(ConfigFormat::Json));
    assert_eq!(ConfigFormat::from_extension("JSON"), Some(ConfigFormat::Json));
    assert_eq!(ConfigFormat::from_extension("txt"), None);
    assert_eq!(ConfigFormat::from_extension(""), None);
}

#[test]
fn test_config_format_from_path() {
    assert_eq!(ConfigFormat::from_path("config.toml"), Some(ConfigFormat::Toml));
    assert_eq!(ConfigFormat::from_path("config.yaml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_path("config.yml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_path("config.json"), Some(ConfigFormat::Json));
    assert_eq!(ConfigFormat::from_path("/path/to/config.toml"), Some(ConfigFormat::Toml));
    assert_eq!(ConfigFormat::from_path("config.txt"), None);
    assert_eq!(ConfigFormat::from_path("config"), None);
}

#[test]
fn test_config_loader_creation() {
    let loader = ConfigLoader::new("config.toml", ConfigFormat::Toml);
    // 只能测试创建成功，因为字段是私有的
    
    let loader_result = ConfigLoader::from_path("config.toml");
    assert!(loader_result.is_ok());
    
    let loader_result = ConfigLoader::from_path("config.yaml");
    assert!(loader_result.is_ok());
    
    let loader_result = ConfigLoader::from_path("config.json");
    assert!(loader_result.is_ok());
    
    let loader_result = ConfigLoader::from_path("config.txt");
    assert!(loader_result.is_err());
}

#[test]
fn test_config_loader_parse_content() {
    // 测试 TOML 解析 - 使用默认配置的 TOML 格式
    let loader = ConfigLoader::new("", ConfigFormat::Toml);
    let config = RustCloudConfig::default();
    let valid_toml = toml::to_string(&config).unwrap();
    assert!(loader.parse_content(&valid_toml).is_ok());
    
    let invalid_toml = "invalid toml content";
    assert!(loader.parse_content(invalid_toml).is_err());
    
    // 测试 YAML 解析 - 使用默认配置
    let loader = ConfigLoader::new("", ConfigFormat::Yaml);
    let config = RustCloudConfig::default();
    let valid_yaml = serde_yaml::to_string(&config).unwrap();
    assert!(loader.parse_content(&valid_yaml).is_ok());
    
    let invalid_yaml = "invalid: yaml: content: [";
    assert!(loader.parse_content(invalid_yaml).is_err());
    
    // 测试 JSON 解析 - 使用默认配置
    let loader = ConfigLoader::new("", ConfigFormat::Json);
    let config = RustCloudConfig::default();
    let valid_json = serde_json::to_string(&config).unwrap();
    assert!(loader.parse_content(&valid_json).is_ok());
    
    let invalid_json = "{ invalid json }";
    assert!(loader.parse_content(invalid_json).is_err());
}

#[test]
fn test_config_loader_file_operations() {
    // 测试加载不存在的文件
    let loader = ConfigLoader::new("non_existent_file.toml", ConfigFormat::Toml);
    assert!(loader.load().is_err());
    
    // 测试创建默认配置文件（使用临时文件）
    let temp_file = NamedTempFile::with_suffix(".json").unwrap();
    let temp_path = temp_file.path().to_str().unwrap();
    
    let loader = ConfigLoader::new(temp_path, ConfigFormat::Json);
    assert!(loader.create_default_config().is_ok());
    
    // 验证创建的文件可以被加载
    let loader = ConfigLoader::from_path(temp_path).unwrap();
    let config = loader.load().unwrap();
    assert_eq!(config.application.name, "rustcloud-gateway");
}

// ================== RustCloudConfig 测试 ==================

#[test]
fn test_rustcloud_config_default() {
    let config = RustCloudConfig::default();
    assert_eq!(config.application.name, "rustcloud-app");
    assert_eq!(config.application.version, "1.0.0");
    assert_eq!(config.application.port, 8080);
    assert_eq!(config.registry.registry_type, RegistryType::Nacos);
    assert_eq!(config.registry.server_addr, "127.0.0.1:8848");
    assert!(config.circuit_breaker.enabled);
    assert_eq!(config.transport.timeout, 5000);
}

#[test]
fn test_rustcloud_config_file_operations() {
    let config = RustCloudConfig::create_example_config();
    
    // 测试 TOML 文件操作
    let temp_toml = NamedTempFile::with_suffix(".toml").unwrap();
    let toml_path = temp_toml.path();
    assert!(config.save_to_file(toml_path).is_ok());
    
    let loaded_config = RustCloudConfig::from_file(toml_path).unwrap();
    assert_eq!(config.application.name, loaded_config.application.name);
    
    // 测试 YAML 文件操作
    let temp_yaml = NamedTempFile::with_suffix(".yaml").unwrap();
    let yaml_path = temp_yaml.path();
    assert!(config.save_to_file(yaml_path).is_ok());
    
    let loaded_config = RustCloudConfig::from_file(yaml_path).unwrap();
    assert_eq!(config.application.name, loaded_config.application.name);
    
    // 测试 JSON 文件操作
    let temp_json = NamedTempFile::with_suffix(".json").unwrap();
    let json_path = temp_json.path();
    assert!(config.save_to_file(json_path).is_ok());
    
    let loaded_config = RustCloudConfig::from_file(json_path).unwrap();
    assert_eq!(config.application.name, loaded_config.application.name);
    
    // 测试不支持的文件格式（默认使用 YAML）
    let temp_unknown = NamedTempFile::with_suffix(".unknown").unwrap();
    let unknown_path = temp_unknown.path();
    assert!(config.save_to_file(unknown_path).is_ok());
    
    let loaded_config = RustCloudConfig::from_file(unknown_path).unwrap();
    assert_eq!(config.application.name, loaded_config.application.name);
}

#[test]
fn test_rustcloud_config_format_conversions() {
    let config = RustCloudConfig::create_example_config();
    
    // 测试 TOML 转换
    let toml_str = config.to_toml().unwrap();
    assert!(toml_str.contains("rustcloud-gateway"));
    let from_toml = RustCloudConfig::from_toml(&toml_str).unwrap();
    assert_eq!(config.application.name, from_toml.application.name);
    
    // 测试 YAML 转换
    let yaml_str = config.to_yaml().unwrap();
    assert!(yaml_str.contains("rustcloud-gateway"));
    let from_yaml = RustCloudConfig::from_yaml(&yaml_str).unwrap();
    assert_eq!(config.application.name, from_yaml.application.name);
    
    // 测试 JSON 转换
    let json_str = config.to_json().unwrap();
    assert!(json_str.contains("rustcloud-gateway"));
    let from_json = RustCloudConfig::from_json(&json_str).unwrap();
    assert_eq!(config.application.name, from_json.application.name);
}

#[test]
fn test_rustcloud_config_validation() {
    let mut config = RustCloudConfig::default();
    assert!(config.validate().is_ok());
    
    // 测试空应用名称
    config.application.name = "".to_string();
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Application name cannot be empty"));
    
    // 恢复应用名称，测试空注册中心地址
    config.application.name = "test-app".to_string();
    config.registry.server_addr = "".to_string();
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Registry server address cannot be empty"));
    
    // 恢复注册中心地址，测试空网关地址
    config.registry.server_addr = "127.0.0.1:8848".to_string();
    config.gateway.server_addr = "".to_string();
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Gateway server address cannot be empty"));
}

// ================ 补充更全面的配置测试 ================

#[test]
fn test_config_format_comprehensive() {
    // 测试所有ConfigFormat的Display实现
    let formats = [ConfigFormat::Toml, ConfigFormat::Yaml, ConfigFormat::Json];
    let expected_strings = ["toml", "yaml", "json"];
    
    for (format, expected) in formats.iter().zip(expected_strings.iter()) {
        assert_eq!(format.to_string(), *expected);
    }
    
    // 测试所有支持的文件扩展名
    let test_cases = [
        ("toml", Some(ConfigFormat::Toml)),
        ("TOML", Some(ConfigFormat::Toml)),
        ("yaml", Some(ConfigFormat::Yaml)),
        ("YAML", Some(ConfigFormat::Yaml)),
        ("yml", Some(ConfigFormat::Yaml)),
        ("YML", Some(ConfigFormat::Yaml)),
        ("json", Some(ConfigFormat::Json)),
        ("JSON", Some(ConfigFormat::Json)),
        ("txt", None),
        ("xml", None),
        ("ini", None),
        ("", None),
        ("config", None),
    ];
    
    for (extension, expected) in test_cases {
        assert_eq!(ConfigFormat::from_extension(extension), expected, 
                  "Extension '{}' should return {:?}", extension, expected);
    }
    
    // 测试各种路径格式
    let path_test_cases = [
        ("/home/user/config.toml", Some(ConfigFormat::Toml)),
        ("./config.yaml", Some(ConfigFormat::Yaml)),
        ("../config.yml", Some(ConfigFormat::Yaml)),
        ("config.json", Some(ConfigFormat::Json)),
        ("C:\\Windows\\config.toml", Some(ConfigFormat::Toml)),
        ("/var/lib/app/config.YAML", Some(ConfigFormat::Yaml)),
        ("config", None),
        ("config.", None),
        (".toml", None), // 没有文件名，只有扩展名
        ("path/without/extension", None),
    ];
    
    for (path, expected) in path_test_cases {
        assert_eq!(ConfigFormat::from_path(path), expected,
                  "Path '{}' should return {:?}", path, expected);
    }
}

#[test]
fn test_config_loader_comprehensive() {
    // 测试ConfigLoader::new与不同参数
    let test_cases = [
        ("config.toml", ConfigFormat::Toml),
        ("config.yaml", ConfigFormat::Yaml),
        ("config.json", ConfigFormat::Json),
        ("/absolute/path/config.toml", ConfigFormat::Toml),
        ("./relative/config.yaml", ConfigFormat::Yaml),
        ("../parent/config.json", ConfigFormat::Json),
        ("", ConfigFormat::Toml), // 空路径也应该可以创建
        ("no-extension", ConfigFormat::Yaml),
    ];
    
    for (path, format) in test_cases {
        let loader = ConfigLoader::new(path, format);
        // 只能验证创建成功，因为字段是私有的
        // 但可以通过其他方法间接验证
    }
    
    // 测试ConfigLoader::from_path的所有有效情况
    let valid_paths = [
        "config.toml",
        "config.yaml", 
        "config.yml",
        "config.json",
        "/path/to/config.TOML",
        "./config.YAML",
        "../config.JSON",
    ];
    
    for path in valid_paths {
        let result = ConfigLoader::from_path(path);
        assert!(result.is_ok(), "Path '{}' should be valid", path);
    }
    
    // 测试ConfigLoader::from_path的所有无效情况
    let invalid_paths = [
        "config.txt",
        "config.xml",
        "config.ini",
        "config",
        "config.",
        "file.unknown",
        "no_extension",
    ];
    
    for path in invalid_paths {
        let result = ConfigLoader::from_path(path);
        assert!(result.is_err(), "Path '{}' should be invalid", path);
    }
}

#[test]
fn test_config_loader_parse_content_comprehensive() {
    let default_config = RustCloudConfig::default();
    let example_config = RustCloudConfig::create_example_config();
    
    // 测试TOML解析 - 不同配置
    let toml_loader = ConfigLoader::new("", ConfigFormat::Toml);
    
    let default_toml = toml::to_string(&default_config).unwrap();
    let example_toml = toml::to_string(&example_config).unwrap();
    
    assert!(toml_loader.parse_content(&default_toml).is_ok());
    assert!(toml_loader.parse_content(&example_toml).is_ok());
    
    // 测试各种无效TOML
    let invalid_toml_cases = [
        "invalid toml",
        "[incomplete",
        "key = ",
        "[section\nkey = value", // 缺少闭合括号
        "key = value\n[\n", // 空section名
        "\x00invalid", // 包含空字符
    ];
    
    for invalid_toml in invalid_toml_cases {
        assert!(toml_loader.parse_content(invalid_toml).is_err(), 
               "TOML '{}' should be invalid", invalid_toml);
    }
    
    // 测试YAML解析 - 不同配置
    let yaml_loader = ConfigLoader::new("", ConfigFormat::Yaml);
    
    let default_yaml = serde_yaml::to_string(&default_config).unwrap();
    let example_yaml = serde_yaml::to_string(&example_config).unwrap();
    
    assert!(yaml_loader.parse_content(&default_yaml).is_ok());
    assert!(yaml_loader.parse_content(&example_yaml).is_ok());
    
    // 测试各种无效YAML
    let invalid_yaml_cases = [
        "invalid: yaml: [",
        "---\n[invalid",
        "key:\nvalue",
        "- item1\n- item2\n[invalid]",
        "\t\tinvalid_tab_indent",
        "key: value\n  invalid_indent",
    ];
    
    for invalid_yaml in invalid_yaml_cases {
        assert!(yaml_loader.parse_content(invalid_yaml).is_err(),
               "YAML '{}' should be invalid", invalid_yaml);
    }
    
    // 测试JSON解析 - 不同配置
    let json_loader = ConfigLoader::new("", ConfigFormat::Json);
    
    let default_json = serde_json::to_string(&default_config).unwrap();
    let example_json = serde_json::to_string(&example_config).unwrap();
    
    assert!(json_loader.parse_content(&default_json).is_ok());
    assert!(json_loader.parse_content(&example_json).is_ok());
    
    // 测试各种无效JSON
    let invalid_json_cases = [
        "{ invalid json }",
        "{\"key\": }",
        "[1, 2, 3,]", // 尾随逗号
        "{\"key\": \"value\",}", // 尾随逗号
        "{'key': 'value'}", // 单引号
        "{key: 'value'}", // 无引号键
        "undefined",
        "null", // 虽然是有效JSON，但不是对象
        "[]", // 数组而非对象
    ];
    
    for invalid_json in invalid_json_cases {
        assert!(json_loader.parse_content(invalid_json).is_err(),
               "JSON '{}' should be invalid", invalid_json);
    }
}

#[test]
fn test_rustcloud_config_comprehensive_validation() {
    let mut config = RustCloudConfig::default();
    
    // 恢复注册中心地址，测试空网关地址
    config.registry.server_addr = "127.0.0.1:8848".to_string();
    config.gateway.server_addr = "".to_string();
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Gateway server address cannot be empty"));
    
    // 测试空路由路径
    config.gateway.server_addr = "0.0.0.0:8080".to_string();
    config.gateway.routes.push(rustcloud_core::RouteConfig {
        path_prefix: "".to_string(),
        service_name: "test-service".to_string(),
        rewrite_path: true,
        enable_cache: false,
        cache_ttl: 300,
    });
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Route path prefix cannot be empty"));
    
    // 测试空服务名称
    config.gateway.routes.clear();
    config.gateway.routes.push(rustcloud_core::RouteConfig {
        path_prefix: "/api/test".to_string(),
        service_name: "".to_string(),
        rewrite_path: true,
        enable_cache: false,
        cache_ttl: 300,
    });
    let result = config.validate();
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Route service name cannot be empty"));
}

#[test]
fn test_rustcloud_config_create_example() {
    let config = RustCloudConfig::create_example_config();
    
    assert_eq!(config.application.name, "rustcloud-gateway");
    assert_eq!(config.application.version, "1.0.0");
    assert_eq!(config.application.port, 8080);
    
    assert_eq!(config.gateway.server_addr, "0.0.0.0:8080");
    assert_eq!(config.gateway.routes.len(), 3);
    
    // 验证路由配置
    let user_route = &config.gateway.routes[0];
    assert_eq!(user_route.path_prefix, "/api/v1/users");
    assert_eq!(user_route.service_name, "user-service");
    assert!(user_route.rewrite_path);
    assert!(user_route.enable_cache);
    assert_eq!(user_route.cache_ttl, 300);
    
    // 验证过滤器配置
    assert!(config.gateway.filters.auth.enabled);
    assert!(config.gateway.filters.auth.api_key_required);
    assert!(config.gateway.filters.rate_limit.enabled);
    assert_eq!(config.gateway.filters.rate_limit.requests_per_minute, 100);
}

#[test]
fn test_rustcloud_config_invalid_format_parsing() {
    // 测试无效的 TOML
    let invalid_toml = "this is not valid toml at all";
    let result = RustCloudConfig::from_toml(invalid_toml);
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Failed to parse TOML config"));
    
    // 测试无效的 YAML
    let invalid_yaml = "[invalid: yaml: syntax";
    let result = RustCloudConfig::from_yaml(invalid_yaml);
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Failed to parse YAML config"));
    
    // 测试无效的 JSON
    let invalid_json = "{ this is not valid json }";
    let result = RustCloudConfig::from_json(invalid_json);
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Failed to parse JSON config"));
}

#[test]
fn test_rustcloud_config_file_read_errors() {
    // 测试读取不存在的文件
    let result = RustCloudConfig::from_file("non_existent_file.toml");
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Failed to read config file"));
}

// ================== 旧的测试用例（保留） ==================

// 保留原有的基本测试用例

#[test]
fn test_config_loader_file_not_found() {
    let loader = ConfigLoader::new("non_existent_file.toml", ConfigFormat::Toml);
    assert!(loader.load().is_err());
}

#[test]
fn test_config_loader_parse_errors() {
    let invalid_toml = "this is not valid toml";
    let loader = ConfigLoader::new("", ConfigFormat::Toml);
    assert!(loader.parse_content(invalid_toml).is_err());

    let invalid_yaml = ": not valid yaml";
    let loader = ConfigLoader::new("", ConfigFormat::Yaml);
    assert!(loader.parse_content(invalid_yaml).is_err());

    let invalid_json = "{ not: valid, json }";
    let loader = ConfigLoader::new("", ConfigFormat::Json);
    assert!(loader.parse_content(invalid_json).is_err());
}

#[test]
fn test_config_loader_from_path() {
    assert!(matches!(ConfigLoader::from_path("config.toml"), Ok(_)));
    assert!(matches!(ConfigLoader::from_path("config.yml"), Ok(_)));
    assert!(matches!(ConfigLoader::from_path("config.yaml"), Ok(_)));
    assert!(matches!(ConfigLoader::from_path("config.json"), Ok(_)));
    assert!(ConfigLoader::from_path("config.txt").is_err());
}

#[test]
fn test_config_loader_load_from_temp_file() {
    let config = RustCloudConfig::create_example_config();
    let toml_content = toml::to_string(&config).unwrap();

    use tempfile::Builder;

    let mut temp_file = Builder::new().suffix(".toml").tempfile().unwrap();
    temp_file.write_all(toml_content.as_bytes()).unwrap();

    let loader = ConfigLoader::from_path(temp_file.path().to_str().unwrap()).unwrap();
    let loaded_config = loader.load().unwrap();

    assert_eq!(loaded_config.application.name, config.application.name);
}

#[test]
fn test_config_validation() {
    let mut config = RustCloudConfig::default();
    assert!(config.validate().is_ok());
    
    // 测试空应用名
    config.application.name = "".to_string();
    assert!(config.validate().is_err());
    
    // 恢复应用名，测试空注册中心地址
    config.application.name = "test-app".to_string();
    config.registry.server_addr = "".to_string();
    assert!(config.validate().is_err());
}

#[test]
fn test_config_serialization() {
    let config = RustCloudConfig::create_example_config();
    
    // TOML
    let toml_str = config.to_toml().unwrap();
    let toml_config = RustCloudConfig::from_toml(&toml_str).unwrap();
    assert_eq!(config.application.name, toml_config.application.name);
    
    // YAML
    let yaml_str = config.to_yaml().unwrap();
    let yaml_config = RustCloudConfig::from_yaml(&yaml_str).unwrap();
    assert_eq!(config.application.name, yaml_config.application.name);
    
    // JSON
    let json_str = config.to_json().unwrap();
    let json_config = RustCloudConfig::from_json(&json_str).unwrap();
    assert_eq!(config.application.name, json_config.application.name);
}

#[test]
fn test_config_format_detection() {
    assert_eq!(ConfigFormat::from_extension("toml"), Some(ConfigFormat::Toml));
    assert_eq!(ConfigFormat::from_extension("yaml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("yml"), Some(ConfigFormat::Yaml));
    assert_eq!(ConfigFormat::from_extension("json"), Some(ConfigFormat::Json));
    assert_eq!(ConfigFormat::from_extension("unknown"), None);
}

#[test]
fn test_config_source_priority() {
    let embedded = ConfigSource::Embedded {
        config: RustCloudConfig::default(),
    };
    let file = ConfigSource::File {
        path: "config.toml".to_string(),
        format: ConfigFormat::Toml,
    };
    let env = ConfigSource::Environment {
        prefix: "RUSTCLOUD".to_string(),
    };
    let remote = ConfigSource::Remote {
        url: "http://config-server/config".to_string(),
        format: ConfigFormat::Json,
        auth: None,
    };
    
    assert!(embedded.priority() < file.priority());
    assert!(file.priority() < env.priority());
    assert!(env.priority() < remote.priority());
}

#[tokio::test]
async fn test_config_manager_basic_operations() {
    let (mut manager, _receiver) = ConfigManager::new(Duration::from_secs(30));
    
    manager.add_source(ConfigSource::Embedded {
        config: RustCloudConfig::create_example_config(),
    });
    
    let config = manager.load_config().await.unwrap();
    assert_eq!(config.application.name, "rustcloud-gateway");
    
    // 测试手动重载
    let result = manager.reload_config().await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_config_manager_builder() {
    let result = ConfigManagerBuilder::new()
        .reload_interval(Duration::from_secs(10))
        .add_source(ConfigSource::Embedded {
            config: RustCloudConfig::create_example_config(),
        })
        .build()
        .await;
    
    assert!(result.is_ok());
    let (_manager, receiver) = result.unwrap();
    let config = receiver.borrow().clone();
    assert_eq!(config.application.name, "rustcloud-gateway");
}

#[tokio::test]
async fn test_config_manager_no_sources() {
    let (manager, _receiver) = ConfigManager::new(Duration::from_secs(30));
    // 由于没有配置源，无法直接测试 load_from_sources，但可以通过其他方式验证
    let config = manager.get_current_config();
    assert_eq!(config.application.name, "rustcloud-app"); // 默认配置
}

// ================== 新增的配置管理器扩展测试 ==================

#[tokio::test]
async fn test_config_manager_multiple_sources() {
    let (mut manager, _receiver) = ConfigManager::new(Duration::from_secs(30));
    
    // 添加多个配置源
    let embedded_config = RustCloudConfig::create_example_config();
    manager.add_source(ConfigSource::Embedded {
        config: embedded_config.clone(),
    });
    
    // 添加环境变量配置源
    manager.add_source(ConfigSource::Environment {
        prefix: "RUSTCLOUD".to_string(),
    });
    
    let config = manager.load_config().await.unwrap();
    assert_eq!(config.application.name, embedded_config.application.name);
}

#[tokio::test]
async fn test_config_manager_source_priority() {
    let (mut manager, _receiver) = ConfigManager::new(Duration::from_secs(30));
    
    // 添加低优先级配置
    let mut low_priority_config = RustCloudConfig::default();
    low_priority_config.application.name = "low-priority-app".to_string();
    manager.add_source(ConfigSource::Embedded {
        config: low_priority_config,
    });
    
    // 添加高优先级配置
    let mut high_priority_config = RustCloudConfig::default();
    high_priority_config.application.name = "high-priority-app".to_string();
    manager.add_source(ConfigSource::Environment {
        prefix: "RUSTCLOUD".to_string(),
    });
    
    let config = manager.load_config().await.unwrap();
    // 应该使用低优先级配置，因为环境变量可能不存在
    assert_eq!(config.application.name, "low-priority-app");
}

#[test]
fn test_config_source_priority_values() {
    let embedded = ConfigSource::Embedded {
        config: RustCloudConfig::default(),
    };
    let file = ConfigSource::File {
        path: "config.toml".to_string(),
        format: ConfigFormat::Toml,
    };
    let env = ConfigSource::Environment {
        prefix: "RUSTCLOUD".to_string(),
    };
    let remote = ConfigSource::Remote {
        url: "http://config-server/config".to_string(),
        format: ConfigFormat::Json,
        auth: None,
    };
    
    // 验证优先级排序
    assert!(embedded.priority() < file.priority());
    assert!(file.priority() < env.priority());
    assert!(env.priority() < remote.priority());
    
    // 验证具体数值
    assert_eq!(embedded.priority(), 0);
    assert_eq!(file.priority(), 1);
    assert_eq!(env.priority(), 2);
    assert_eq!(remote.priority(), 3);
}

#[test]
fn test_config_source_display() {
    let embedded = ConfigSource::Embedded {
        config: RustCloudConfig::default(),
    };
    let file = ConfigSource::File {
        path: "config.toml".to_string(),
        format: ConfigFormat::Toml,
    };
    let env = ConfigSource::Environment {
        prefix: "RUSTCLOUD".to_string(),
    };
    let remote = ConfigSource::Remote {
        url: "http://config-server/config".to_string(),
        format: ConfigFormat::Json,
        auth: Some(RemoteAuth::Bearer("Bearer token".to_string())),
    };
    
    assert_eq!(embedded.to_string(), "Embedded");
    assert_eq!(file.to_string(), "File(config.toml: Toml)");
    assert_eq!(env.to_string(), "Environment(RUSTCLOUD)");
    assert_eq!(remote.to_string(), "Remote(http://config-server/config: Json)");
}

#[tokio::test]
async fn test_config_manager_builder_validation() {
    // 测试没有配置源的情况
    let result = ConfigManagerBuilder::new()
        .reload_interval(Duration::from_secs(10))
        .build()
        .await;
    
    // 就算没有配置源，也会使用默认配置
    assert!(result.is_err());
}

#[tokio::test]
async fn test_config_manager_reload() {
    let (mut manager, receiver) = ConfigManagerBuilder::new()
        .reload_interval(Duration::from_millis(100))
        .add_source(ConfigSource::Embedded {
            config: RustCloudConfig::create_example_config(),
        })
        .build()
        .await
        .unwrap();
    
    let initial_config = receiver.borrow().clone();
    assert_eq!(initial_config.application.name, "rustcloud-gateway");
    
    // 手动重载配置
    let reload_result = manager.reload_config().await;
    assert!(reload_result.is_ok());
    
    // 验证配置没有变化（因为源没有变化）
    let reloaded_config = receiver.borrow().clone();
    assert_eq!(reloaded_config.application.name, "rustcloud-gateway");
}

#[tokio::test]
async fn test_config_manager_watch_changes() {
    let (mut manager, mut receiver) = ConfigManagerBuilder::new()
        .reload_interval(Duration::from_millis(50))
        .add_source(ConfigSource::Embedded {
            config: RustCloudConfig::create_example_config(),
        })
        .build()
        .await
        .unwrap();
    
    // 等待一个短时间来让自动重载启动
    tokio::time::sleep(Duration::from_millis(10)).await;
    
    let config = receiver.borrow().clone();
    assert_eq!(config.application.name, "rustcloud-gateway");
    
    // 可以手动停止管理器
    manager.stop_hot_reload().await;
}

#[test]
fn test_config_source_serialization() {
    use serde_json;
    
    let embedded = ConfigSource::Embedded {
        config: RustCloudConfig::default(),
    };
    let serialized = serde_json::to_string(&embedded).unwrap();
    let deserialized: ConfigSource = serde_json::from_str(&serialized).unwrap();
    
    match (embedded, deserialized) {
        (ConfigSource::Embedded { config: c1 }, ConfigSource::Embedded { config: c2 }) => {
            assert_eq!(c1.application.name, c2.application.name);
        }
        _ => panic!("Deserialization failed"),
    }
}

#[test]
fn test_config_loader_edge_cases() {
    // 测试空字符串解析
    let loader = ConfigLoader::new("", ConfigFormat::Json);
    let result = loader.parse_content("");
    assert!(result.is_err());
    
    // 测试只有空白字符的内容
    let loader = ConfigLoader::new("", ConfigFormat::Yaml);
    let result = loader.parse_content("   \n\t  ");
    // YAML 可能会把空内容解析为 null，这可能导致错误
    // 这里我们只验证不会 panic
    let _ = result;
}

// Mock 测试用侎结构
struct MockConfigSource {
    should_fail: bool,
    config: RustCloudConfig,
}

impl MockConfigSource {
    fn new(should_fail: bool) -> Self {
        Self {
            should_fail,
            config: RustCloudConfig::create_example_config(),
        }
    }
    
    async fn load_config(&self) -> Result<RustCloudConfig, String> {
        if self.should_fail {
            Err("Mock error".to_string())
        } else {
            Ok(self.config.clone())
        }
    }
}

#[tokio::test]
async fn test_mock_config_source() {
    let mock_success = MockConfigSource::new(false);
    let config = mock_success.load_config().await.unwrap();
    assert_eq!(config.application.name, "rustcloud-gateway");
    
    let mock_failure = MockConfigSource::new(true);
    let result = mock_failure.load_config().await;
    assert!(result.is_err());
    assert_eq!(result.unwrap_err(), "Mock error");
}

